<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请输入手机号', trigger: 'onChange', pattern: /^1[3-9]\d{0,9}$/, },
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[
          { required: true, message: '请输入密码', trigger: 'onChange', pattern: /^\d{6}$/, },
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
        :loading='isLoading' :disabled='isLoading'  loading-text="加载中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
// import { Notify } from 'vant'
import { MyNotify } from '@/utils/Notify'

import { mapMutations } from 'vuex'

export default {

  data () {
    return {
      formLogin: {
        mobile: '18512345678',
        code: '246810'
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefreshToken']),
    // 点击登录
    async onSubmit () {
      this.isLoading = true// 按钮加载状态
      try {
        const res = await loginAPI(this.formLogin)
        console.log(res)
        // token
        this.setToken(res.data.data.token)
        this.setRefreshToken(res.data.data.refresh_token)
        console.log(res)
        this.isLoading = false
        MyNotify({ type: 'success', message: '登录成功' })
        // 跳转到Layout页面

        // this.$router.replace({
        //   // push跳转后, 可以返回
        // // replace跳转后, 无法返回
        //   path: '/layout'
        // })
        if (this.$route.query.code === '401') {
          this.$router.back()
        } else {
          // 跳转到/layout
          this.$router.push({
            path: '/layout'
          })
        }
      } catch (err) {
        // 登录失败, 按钮放开
        this.isLoading = false
        MyNotify({ type: 'warning', message: '登录失败' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
